[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity, isPopulated } from '@growi/core';
  5. import type {
  6. GroupType,
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  8. } from '@growi/core';
  9. import {
  10. isClient, pagePathUtils, pathUtils,
  11. } from '@growi/core/dist/utils';
  12. import ExtensibleCustomError from 'extensible-custom-error';
  13. import type {
  14. GetServerSideProps, GetServerSidePropsContext,
  15. } from 'next';
  16. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  17. import dynamic from 'next/dynamic';
  18. import Head from 'next/head';
  19. import { useRouter } from 'next/router';
  20. import superjson from 'superjson';
  21. import { useEditorModeClassName } from '~/client/services/layout';
  22. import { PageView } from '~/components/Page/PageView';
  23. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  24. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  25. import type { CrowiRequest } from '~/interfaces/crowi-request';
  26. import type { EditorConfig } from '~/interfaces/editor-settings';
  27. import type { IPageGrantData } from '~/interfaces/page';
  28. import type { RendererConfig } from '~/interfaces/services/renderer';
  29. import type { PageModel, PageDocument } from '~/server/models/page';
  30. import type { PageRedirectModel } from '~/server/models/page-redirect';
  31. import {
  32. useCurrentUser,
  33. useIsForbidden, useIsSharedUser,
  34. useIsEnabledStaleNotification, useIsIdenticalPath,
  35. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  36. useDefaultIndentSize, useIsIndentSizeForced,
  37. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  38. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  39. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  40. useEditorConfig, useIsAllReplyShown, useIsUploadAllFileAllowed, useIsUploadEnabled, useIsContainerFluid, useIsNotCreatable,
  41. } from '~/stores/context';
  42. import { useEditingMarkdown } from '~/stores/editor';
  43. import {
  44. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  45. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  46. } from '~/stores/page';
  47. import { useRedirectFrom } from '~/stores/page-redirect';
  48. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  49. import { useSelectedGrant } from '~/stores/ui';
  50. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  51. import loggerFactory from '~/utils/logger';
  52. import { BasicLayout } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  54. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  55. import type { NextPageWithLayout } from './_app.page';
  56. import type { CommonProps } from './utils/commons';
  57. import {
  58. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  59. } from './utils/commons';
  60. declare global {
  61. // eslint-disable-next-line vars-on-top, no-var
  62. var globalEmitter: EventEmitter;
  63. }
  64. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  65. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  66. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  67. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  68. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  69. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  70. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  71. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  72. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  73. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  74. const logger = loggerFactory('growi:pages:all');
  75. const {
  76. isPermalink: _isPermalink, isCreatablePage,
  77. } = pagePathUtils;
  78. const { removeHeadingSlash } = pathUtils;
  79. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  80. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  81. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  82. {
  83. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  84. return v?.data != null
  85. && v?.data.toObject != null
  86. && v?.meta != null
  87. && isIPageInfoForEntity(v.meta);
  88. },
  89. serialize: (v) => {
  90. return {
  91. data: superjson.stringify(v.data.toObject()),
  92. meta: superjson.stringify(v.meta),
  93. };
  94. },
  95. deserialize: (v) => {
  96. return {
  97. data: superjson.parse(v.data),
  98. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  99. };
  100. },
  101. },
  102. 'IPageToShowRevisionWithMetaTransformer',
  103. );
  104. // GrowiContextualSubNavigation for NOT shared page
  105. type GrowiContextualSubNavigationProps = {
  106. isLinkSharingDisabled: boolean,
  107. }
  108. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  109. const { isLinkSharingDisabled } = props;
  110. const { data: currentPage } = useSWRxCurrentPage();
  111. return (
  112. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  113. );
  114. };
  115. type Props = CommonProps & {
  116. pageWithMeta: IPageToShowRevisionWithMeta | null,
  117. // pageUser?: any,
  118. redirectFrom?: string;
  119. // shareLinkId?: string;
  120. isLatestRevision?: boolean,
  121. isIdenticalPathPage?: boolean,
  122. isForbidden: boolean,
  123. isNotFound: boolean,
  124. isNotCreatable: boolean,
  125. // isAbleToDeleteCompletely: boolean,
  126. templateTagData?: string[],
  127. templateBodyData?: string,
  128. isSearchServiceConfigured: boolean,
  129. isSearchServiceReachable: boolean,
  130. isSearchScopeChildrenAsDefault: boolean,
  131. isEnabledMarp: boolean,
  132. isSlackConfigured: boolean,
  133. // isMailerSetup: boolean,
  134. isAclEnabled: boolean,
  135. // hasSlackConfig: boolean,
  136. drawioUri: string | null,
  137. noCdn: string,
  138. // highlightJsStyle: string,
  139. isAllReplyShown: boolean,
  140. isContainerFluid: boolean,
  141. editorConfig: EditorConfig,
  142. isEnabledStaleNotification: boolean,
  143. isEnabledAttachTitleHeader: boolean,
  144. // isEnabledLinebreaks: boolean,
  145. // isEnabledLinebreaksInComments: boolean,
  146. adminPreferredIndentSize: number,
  147. isIndentSizeForced: boolean,
  148. disableLinkSharing: boolean,
  149. skipSSR: boolean,
  150. ssrMaxRevisionBodyLength: number,
  151. grantData?: IPageGrantData,
  152. rendererConfig: RendererConfig,
  153. };
  154. const Page: NextPageWithLayout<Props> = (props: Props) => {
  155. // register global EventEmitter
  156. if (isClient() && window.globalEmitter == null) {
  157. window.globalEmitter = new EventEmitter();
  158. }
  159. const router = useRouter();
  160. useCurrentUser(props.currentUser ?? null);
  161. // commons
  162. useEditorConfig(props.editorConfig);
  163. useCsrfToken(props.csrfToken);
  164. useGrowiCloudUri(props.growiCloudUri);
  165. // page
  166. useIsContainerFluid(props.isContainerFluid);
  167. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  168. useIsForbidden(props.isForbidden);
  169. useIsNotCreatable(props.isNotCreatable);
  170. useRedirectFrom(props.redirectFrom ?? null);
  171. useIsSharedUser(false); // this page cann't be routed for '/share'
  172. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  173. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  174. useIsSearchPage(false);
  175. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. // useNoCdn(props.noCdn);
  184. useDefaultIndentSize(props.adminPreferredIndentSize);
  185. useIsIndentSizeForced(props.isIndentSizeForced);
  186. useDisableLinkSharing(props.disableLinkSharing);
  187. useRendererConfig(props.rendererConfig);
  188. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  189. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  190. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  191. useIsAllReplyShown(props.isAllReplyShown);
  192. useIsUploadAllFileAllowed(props.editorConfig.upload.isUploadAllFileAllowed);
  193. useIsUploadEnabled(props.editorConfig.upload.isUploadEnabled);
  194. const { pageWithMeta } = props;
  195. const pageId = pageWithMeta?.data._id;
  196. const revisionBody = pageWithMeta?.data.revision?.body;
  197. useCurrentPathname(props.currentPathname);
  198. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  199. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  200. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  201. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  202. const { mutate: mutateIsNotFound } = useIsNotFound();
  203. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  204. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  205. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  206. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  207. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  208. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  209. useSetupGlobalSocket();
  210. useSetupGlobalSocketForPage(pageId);
  211. // Store initial data (When revisionBody is not SSR)
  212. useEffect(() => {
  213. if (!props.skipSSR) {
  214. return;
  215. }
  216. if (currentPageId != null && !props.isNotFound) {
  217. const mutatePageData = async() => {
  218. const pageData = await mutateCurrentPage();
  219. mutateEditingMarkdown(pageData?.revision.body);
  220. };
  221. // If skipSSR is true, use the API to retrieve page data.
  222. // Because pageWIthMeta does not contain revision.body
  223. mutatePageData();
  224. }
  225. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  226. // sync grant data
  227. useEffect(() => {
  228. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  229. mutateSelectedGrant(grantDataToApply);
  230. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  231. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  232. useEffect(() => {
  233. const decodedURI = decodeURI(window.location.pathname);
  234. if (isClient() && decodedURI !== props.currentPathname) {
  235. const { search, hash } = window.location;
  236. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  237. }
  238. }, [props.currentPathname, router]);
  239. // initialize mutateEditingMarkdown only once per page
  240. // need to include useCurrentPathname not useCurrentPagePath
  241. useEffect(() => {
  242. if (props.currentPathname != null) {
  243. mutateEditingMarkdown(revisionBody);
  244. }
  245. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  246. useEffect(() => {
  247. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  248. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  249. useEffect(() => {
  250. mutateCurrentPageId(pageId ?? null);
  251. }, [mutateCurrentPageId, pageId]);
  252. useEffect(() => {
  253. mutateIsNotFound(props.isNotFound);
  254. }, [mutateIsNotFound, props.isNotFound]);
  255. useEffect(() => {
  256. mutateIsLatestRevision(props.isLatestRevision);
  257. }, [mutateIsLatestRevision, props.isLatestRevision]);
  258. useEffect(() => {
  259. mutateTemplateTagData(props.templateTagData);
  260. }, [props.templateTagData, mutateTemplateTagData]);
  261. useEffect(() => {
  262. mutateTemplateBodyData(props.templateBodyData);
  263. }, [props.templateBodyData, mutateTemplateBodyData]);
  264. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  265. // So preferentially take page data from useSWRxCurrentPage
  266. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  267. const title = generateCustomTitleForPage(props, pagePath);
  268. return (
  269. <>
  270. <Head>
  271. <title>{title}</title>
  272. </Head>
  273. <div className="dynamic-layout-root justify-content-between">
  274. <nav className="sticky-top">
  275. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  276. </nav>
  277. <DisplaySwitcher
  278. pageView={(
  279. <PageView
  280. pagePath={pagePath}
  281. initialPage={pageWithMeta?.data}
  282. rendererConfig={props.rendererConfig}
  283. />
  284. )}
  285. />
  286. <PageStatusAlert />
  287. </div>
  288. </>
  289. );
  290. };
  291. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  292. const editorModeClassName = useEditorModeClassName();
  293. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  294. };
  295. type LayoutProps = Props & {
  296. children?: ReactNode
  297. }
  298. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  299. // init sidebar config with UserUISettings and sidebarConfig
  300. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  301. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  302. };
  303. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  304. return (
  305. <>
  306. <GrowiPluginsActivator />
  307. <DrawioViewerScript />
  308. <Layout {...page.props}>
  309. {page}
  310. </Layout>
  311. <UnsavedAlertDialog />
  312. <DescendantsPageListModal />
  313. <DrawioModal />
  314. <HandsontableModal />
  315. <QuestionnaireModalManager />
  316. <TemplateModal />
  317. <LinkEditModal />
  318. <TagEditModal />
  319. </>
  320. );
  321. };
  322. function getPageIdFromPathname(currentPathname: string): string | null {
  323. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  324. }
  325. class MultiplePagesHitsError extends ExtensibleCustomError {
  326. pagePath: string;
  327. constructor(pagePath: string) {
  328. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  329. this.pagePath = pagePath;
  330. }
  331. }
  332. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  333. const { model: mongooseModel } = await import('mongoose');
  334. const req: CrowiRequest = context.req as CrowiRequest;
  335. const { crowi } = req;
  336. const { revisionId } = req.query;
  337. const Page = crowi.model('Page') as PageModel;
  338. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  339. const { pageService, configManager, pageGrantService } = crowi;
  340. let currentPathname = props.currentPathname;
  341. const pageId = getPageIdFromPathname(currentPathname);
  342. const isPermalink = _isPermalink(currentPathname);
  343. const { user } = req;
  344. if (!isPermalink) {
  345. // check redirects
  346. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  347. if (chains != null) {
  348. // overwrite currentPathname
  349. currentPathname = chains.end.toPath;
  350. props.currentPathname = currentPathname;
  351. // set redirectFrom
  352. props.redirectFrom = chains.start.fromPath;
  353. }
  354. // check whether the specified page path hits to multiple pages
  355. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  356. if (count > 1) {
  357. throw new MultiplePagesHitsError(currentPathname);
  358. }
  359. }
  360. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  361. const page = pageWithMeta?.data as unknown as PageDocument;
  362. // add user to seen users
  363. if (page != null && user != null) {
  364. await page.seen(user);
  365. }
  366. // populate & check if the revision is latest
  367. if (page != null) {
  368. page.initLatestRevisionField(revisionId);
  369. props.isLatestRevision = page.isLatestRevision();
  370. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  371. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  372. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  373. }
  374. if (page == null && user != null) {
  375. const templateData = await Page.findTemplate(props.currentPathname);
  376. if (templateData != null) {
  377. props.templateTagData = templateData.templateTags as string[];
  378. props.templateBodyData = templateData.templateBody as string;
  379. }
  380. // apply parent page grant, without groups that user isn't related to
  381. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  382. if (ancestor != null) {
  383. ancestor.populate('grantedGroups.item');
  384. const userRelatedGrantedGroups = (await pageGrantService.getUserRelatedGrantedGroups(ancestor, user)).map((group) => {
  385. if (isPopulated(group.item)) {
  386. return {
  387. id: group.item._id,
  388. name: group.item.name,
  389. type: group.type,
  390. };
  391. }
  392. return null;
  393. }).filter((info): info is NonNullable<{id: string, name: string, type: GroupType}> => info != null);
  394. props.grantData = {
  395. grant: ancestor.grant,
  396. userRelatedGrantedGroups,
  397. };
  398. }
  399. }
  400. props.pageWithMeta = pageWithMeta;
  401. }
  402. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  403. const req: CrowiRequest = context.req as CrowiRequest;
  404. const { crowi } = req;
  405. const Page = crowi.model('Page') as PageModel;
  406. const { currentPathname } = props;
  407. const pageId = getPageIdFromPathname(currentPathname);
  408. const isPermalink = _isPermalink(currentPathname);
  409. const page = props.pageWithMeta?.data;
  410. if (props.isIdenticalPathPage) {
  411. props.isNotCreatable = true;
  412. }
  413. else if (page == null) {
  414. props.isNotFound = true;
  415. props.isNotCreatable = !isCreatablePage(currentPathname);
  416. // check the page is forbidden or just does not exist.
  417. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  418. props.isForbidden = count > 0;
  419. }
  420. else {
  421. props.isNotFound = page.isEmpty;
  422. props.isNotCreatable = false;
  423. props.isForbidden = false;
  424. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  425. if (isPermalink && page.isEmpty) {
  426. props.currentPathname = page.path;
  427. }
  428. // /path/to/page ==> /62a88db47fed8b2d94f30000
  429. if (!isPermalink && !page.isEmpty) {
  430. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  431. if (!isToppage) {
  432. props.currentPathname = `/${page._id}`;
  433. }
  434. }
  435. }
  436. }
  437. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  438. // const req: CrowiRequest = context.req as CrowiRequest;
  439. // const { crowi } = req;
  440. // const UserModel = crowi.model('User');
  441. // if (isUserPage(props.currentPagePath)) {
  442. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  443. // if (user != null) {
  444. // props.pageUser = JSON.stringify(user.toObject());
  445. // }
  446. // }
  447. // }
  448. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  449. const req: CrowiRequest = context.req as CrowiRequest;
  450. const { crowi } = req;
  451. const {
  452. searchService, configManager, aclService,
  453. } = crowi;
  454. props.isSearchServiceConfigured = searchService.isConfigured;
  455. props.isSearchServiceReachable = searchService.isReachable;
  456. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  457. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  458. // props.isMailerSetup = mailService.isMailerSetup;
  459. props.isAclEnabled = aclService.isAclEnabled();
  460. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  461. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  462. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  463. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  464. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  465. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  466. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  467. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  468. props.editorConfig = {
  469. upload: {
  470. isUploadAllFileAllowed: crowi.fileUploadService.getFileUploadEnabled(),
  471. isUploadEnabled: crowi.fileUploadService.getIsUploadable(),
  472. },
  473. };
  474. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  475. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  476. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  477. props.rendererConfig = {
  478. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  479. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  480. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  481. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  482. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  483. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  484. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  485. // XSS Options
  486. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  487. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  488. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  489. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  490. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  491. };
  492. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  493. }
  494. /**
  495. * for Server Side Translations
  496. * @param context
  497. * @param props
  498. * @param namespacesRequired
  499. */
  500. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  501. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  502. props._nextI18Next = nextI18NextConfig._nextI18Next;
  503. }
  504. const getAction = (props: Props): SupportedActionType => {
  505. if (props.isNotCreatable) {
  506. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  507. }
  508. if (props.isForbidden) {
  509. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  510. }
  511. if (props.isNotFound) {
  512. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  513. }
  514. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  515. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  516. }
  517. return SupportedAction.ACTION_PAGE_VIEW;
  518. };
  519. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  520. const req = context.req as CrowiRequest;
  521. const { user } = req;
  522. const result = await getServerSideCommonProps(context);
  523. // check for presence
  524. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  525. if (!('props' in result)) {
  526. throw new Error('invalid getSSP result');
  527. }
  528. const props: Props = result.props as Props;
  529. if (props.redirectDestination != null) {
  530. return {
  531. redirect: {
  532. permanent: false,
  533. destination: props.redirectDestination,
  534. },
  535. };
  536. }
  537. if (user != null) {
  538. props.currentUser = user.toObject();
  539. }
  540. try {
  541. await injectPageData(context, props);
  542. }
  543. catch (err) {
  544. if (err instanceof MultiplePagesHitsError) {
  545. props.isIdenticalPathPage = true;
  546. }
  547. else {
  548. throw err;
  549. }
  550. }
  551. await injectRoutingInformation(context, props);
  552. injectServerConfigurations(context, props);
  553. await injectNextI18NextConfigurations(context, props, ['translation']);
  554. addActivity(context, getAction(props));
  555. return {
  556. props,
  557. };
  558. };
  559. export default Page;